<?php
/**
 * 请求发送核心类
 */
namespace app\depend;

use app\addon\appLog;

class CarLifeCurl
{
    private static $uri = 'http://api.1cloudsp.com/api/v2/single_send';//短信请求地址
    private static $requestID = null;
    private static $api = null;
    private static $error = null;
    private static $errormessage = null;

    private static $opt = [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_CONNECTTIMEOUT => 50,
        CURLOPT_TIMEOUT => 50,
    ];

    private static function result()
    {
    }
    private static function exec()
    {
        $ch = curl_init();
        curl_setopt_array($ch, self::$opt);
        $data = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
        $errno = curl_errno($ch);
        $errinfo = curl_error($ch);
        
        $curl_err = [
            'http-code' => $httpCode,
            'spend-time' => $curlTime,
            'info' => 'carlifeh5-curl日志',
            'requestID' => self::$requestID,
            'error' => $errno,
            'err_msg' => $errinfo,
            'file' => __FILE__,
            'line' => __LINE__,
            'uri' => self::$api,
            'post-data' => self::$opt[CURLOPT_POSTFIELDS],
            'response-data' => $data
        ];
        curl_close($ch);
        if ($httpCode == 502 || $httpCode == 404 || $httpCode == 500 || $httpCode == 0) {
            $logDir = "error";
        } else {
            $logDir = "logs";
        }
//        appLog::appLog($logDir, $curl_err);

//        var_dump($data);die;
        if ($data === false) {
            return ['error' => '33', 'errormessage' => '请求失败，请稍候重试哦！'];
        } else {
            if (empty($data) || $data == false) {
                $data = [
                    'error' => '1008110',
                    'errormessage' => '请求失败，请稍候重试！',
                ];
            } else {
                if (is_string($data)) {
                    $data = json_decode($data, true);
                    if (isset($data['result'])) {
                        if ($data['result'] == 1) {
                            $data['error'] = ERR_RETURN_OK;
                        } elseif ($data['result'] == '1001' || $data['result'] == '1008' || $data['result'] == '1111') {
                            //身份验证失败
                            $data['error'] = '2001110';
                            $data['errormessage'] = isset($data['msg']) ? $data['msg'] : '';
                        } else {
                            $data['error'] = $data['result'];
                            $data['errormessage'] = isset($data['msg']) ? $data['msg'] : '';
                        }
                    }
                    if (empty($data)) {
                        $data = [
                            'error' => '1008111',
                            'errormessage' => '请求失败，请稍候重试！',
                        ];
                    }
                }
            }
            return $data;
        }
    }

    /**
     * @param string $str
     * 这个是用来调用 车联网内部系统  类型的接口的
     */
    public static function postJsonStr($str = "", $config = [])
    {
        if (is_array($str)) {
            if (!isset($data['requestID'])) {
                $data['requestID'] = isset($_POST['requestID']) ? $_POST['requestID'] : createGuid();
            }
            $str = json_encode($str, JSON_UNESCAPED_UNICODE);
        }
        self::$opt[CURLOPT_URL] = APP_SERV_ROUTE."/iov_gw/internal";
        self::$opt[CURLOPT_POST] = 1;
        self::$opt[CURLOPT_POSTFIELDS] = $str;
        if (is_array($config)) {
            foreach ($config as $k => $v) {
                self::$opt[$k] = $v;
            }
        }
        return self::exec();
    }//end

    /**
     * post方法
     * @param mixed $data 请求参数
     * @param mixed $config 相关配置
     * @return mixed 请求结果
     */
    public static function curlPost($data = '', $config = '')
    {
        self::$opt[CURLOPT_POST] = 1;
        self::$opt[CURLOPT_URL] = self::$uri;
        if (is_array($data) && !empty($data)) {
        
            
            self::$opt[CURLOPT_POSTFIELDS] = http_build_query($data);
            
        }
        
        return self::exec();
    }


    public static function curlPost2($data = '', $config = '', $uploadFile = [])
    {
        self::$opt[CURLOPT_POST] = 1;
        self::$opt[CURLOPT_URL] = self::$uri;
        if (is_array($data) && !empty($data)) {
            !isset($data['appGray']) && defined('APP_GRAY') && APP_GRAY == "1" && $data['appGray'] = "1";   //是否灰度环境
            !isset($data['userId']) && $data['userId'] = session('userid') ? session('userid') : '';
            !isset($data['token']) && $data['token'] = session('login_token') ? session('login_token') : '';
            $userId = $data['userId'];
            $token = $data['token'];
            unset($data['userId']);
            // unset($data['token']);
            if (!isset($data['sign']) || !isset($data['timestamp'])) {
                $timestamp = time();
                $sign = md5($userId . $token . $timestamp);
                $data['userId'] = $userId;
                $data['sign'] = $sign;
                $data['timestamp'] = $timestamp;
            }

            $data['user_ip'] = getClientIp();
            if (!isset($data['requestID'])) {
                $data['requestID'] = isset($_POST['requestID']) ? $_POST['requestID'] : createGuid();
            }
            if (isset($data['api'])) {
                self::$api = $data['api'];
            }
            if (empty($uploadFile)) {
                self::$opt[CURLOPT_POSTFIELDS] = http_build_query($data);
            } else {
                self::buildUploadFileData($data, $uploadFile);
                self::$opt[CURLOPT_POSTFIELDS] = $data;
            }//end if
        } elseif (is_string($data) && !empty($data)) {
            $api = $data;
            self::$api = $data;
            $userId = session('userid') ? session('userid') : '';
            $token = session('login_token') ? session('login_token') : '';
            $timestamp = time();
            $sign = md5($userId . $token . $timestamp);
            $data = array(
                'userId' => $userId,
                'sign' => $sign,
                'timestamp' => $timestamp,
                'api' => $api,
                'user_ip' => getClientIp()
            );
            !isset($data['appGray']) && defined('APP_GRAY') && APP_GRAY == "1" && $data['appGray'] = "1";   //是否灰度环境
            $data['requestID'] = isset($_POST['requestID']) ? $_POST['requestID'] : createGuid();
            if (empty($uploadFile)) {
                self::$opt[CURLOPT_POSTFIELDS] = http_build_query($data);
            } else {
                self::buildUploadFileData($data, $uploadFile);   //组装上传文件功能
                self::$opt[CURLOPT_POSTFIELDS] = $data;
            }
        }
        self::$requestID  = $data['requestID'];
        if (is_array($config)) {
            foreach ($config as $k => $v) {
                self::$opt[$k] = $v;
            }
        }
        return self::exec();
    }

    /**
     * 组装上传文件包内容
     */
    private static function buildUploadFileData(&$data, $uploadFile)
    {
        if (is_array($uploadFile)) {
            foreach ($uploadFile as $k => $v) {
                if (isset($_FILES[$v])) {
                    if ($_FILES[$v]['error'] == UPLOAD_ERR_OK) {
                        $name = $_FILES[$v]['name'];    //原始文件名
                        $type = $_FILES[$v]['type'];   //文件类型
                        $fils = $_FILES[$v]['tmp_name'];   //文件路径
                        $upfiles = curl_file_create($fils, $type, $name);
                        $data[$v] = $upfiles;  //这个 $v 上传文件的 <input type="file" name="name">
                    } else {
                        //这里是上传文件不成功
                    }//end is isset
                }//end is set
            }
        } else {
            if (isset($_FILES[$uploadFile])) {
                if ($_FILES[$uploadFile]['error'] == UPLOAD_ERR_OK) {
                    $name = $_FILES[$uploadFile]['name'];    //原始文件名
                    $type = $_FILES[$uploadFile]['type'];   //文件类型
                    $fils = $_FILES[$uploadFile]['tmp_name'];   //文件路径
                    $upfiles = curl_file_create($fils, $type, $name);
                    $data[$uploadFile] = $upfiles;  //这个 $v 上传文件的 <input type="file" name="name">
                } else {
                    //这里是上传文件不成功
                }//end is isset
            }//end is set
        }//end else
    }//end

    /**
     * post方法
     * @param mixed $data 请求参数
     * @param mixed $config 相关配置
     * @return mixed 请求结果
     * 这个是 APP 用的方法
     */
    public static function appPost($data = '', $config = '', $uploadFile = [])
    {
        self::$opt[CURLOPT_POST] = 1;
        self::$opt[CURLOPT_URL] = self::$uri;
        if (is_array($data) && !empty($data)) {
            !isset($data['appGray']) && defined('APP_GRAY') && APP_GRAY == "1" && $data['appGray'] = "1";   //是否灰度环境
            !isset($data['userId']) && $data['userId'] =  '';
            !isset($data['token']) && $data['token'] =  '';
            $userId = $data['userId'];
            $token = $data['token'];
            if (!isset($data['requestID'])) {
                $data['requestID'] = isset($_POST['requestID']) ? $_POST['requestID'] : createGuid();
            }
            unset($data['token']);
            if (!isset($data['sign']) || !isset($data['timestamp'])) {
                $timestamp = time();
                $sign = md5($userId . $token . $timestamp);
                $data['userId'] = $userId;
                $data['sign'] = $sign;
                $data['timestamp'] = $timestamp;
            }
            if (isset($data['api'])) {
                self::$api = $data['api'];
            }

            if (empty($uploadFile)) {
                self::$opt[CURLOPT_POSTFIELDS] = http_build_query($data);
            } else {
                self::buildUploadFileData($data, $uploadFile);   //组装上传文件功能
                self::$opt[CURLOPT_POSTFIELDS] = $data;
            }
        } elseif (is_string($data) && !empty($data)) {
            $api = $data;
            self::$api = $data;
            $timestamp = time();
            $sign = md5($timestamp);
            $data = array(
                'sign' => $sign,
                'timestamp' => $timestamp,
                'requestID' => createGuid(),
                'api' => $api,
            );
            !isset($data['appGray']) && defined('APP_GRAY') && APP_GRAY == "1" && $data['appGray'] = "1";   //是否灰度环境
            if (empty($uploadFile)) {
                self::$opt[CURLOPT_POSTFIELDS] = http_build_query($data);
            } else {
                self::buildUploadFileData($data, $uploadFile);   //组装上传文件功能
                self::$opt[CURLOPT_POSTFIELDS] = $data;
            }
        }
        self::$requestID  = $data['requestID'];
        if (is_array($config) && !empty($config)) {
            self::$opt =  array_merge(self::$opt, $config);
        }
        return self::exec();
    }
}
